package p2p.peer.command;

import java.util.List;

import p2p.logic.connection.Command;
import p2p.logic.connection.client.Client;
import p2p.logic.connection.communication.message.Message;
import p2p.logic.connection.communication.message.CommandVisitor;
import p2p.logic.log.Logger;
import p2p.peer.ClientManager;
import p2p.peer.command.visitor.GSVisitor;

public class Leave extends Command{
		
	private boolean isAck;
	
	public Leave(){
		
	}
	
	public Leave(Message m, CommandVisitor v, boolean isAck) {
		super(v);
		this.message = m;
		this.visitor = v;
		this.isAck = isAck;
	}
	
	public Leave(CommandVisitor v, Message m, boolean isAck){
		super(v);
		this.message = m;
		this.isAck = isAck;
	}

	public int getCommandCode() {
		return 1;
	}

	@Override
	public void execute() {
		
		ClientManager manager = ((GSVisitor) getVisitor()).getManager();
		
		if (isAck){
			
			for (int i = 0; i < manager.getClients().size(); i++){
				
				Client c = manager.getClients().get(i);
				
				if (c.getIp().equals(this.message.getRecipientIp()) && c.getPort() == this.message.getRecipientPort()){
					manager.removeClient(i);
				}
			}
			

		}else {
			
			List<Client> newNeighbor = this.message.clientList();
			Client oldNeighbor = new Client(this.message.getSenderIp(), this.message.getSenderPort());
			
			manager.removeClient(oldNeighbor);
			
			manager.addClients(newNeighbor);
			
		}
		
		Logger.consoleLog("Neighborlist: " + manager.getPeer().getId() + ": " + manager.toString());
		
	}
	

}
